/*
	This file is part of the OdinMS Maple Story Server
    Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc>
		       Matthias Butz <matze@odinms.de>
		       Jan Christian Meyer <vimes@odinms.de>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation version 3 as published by
    the Free Software Foundation. You may not use, modify or distribute
    this program under any other version of the GNU Affero General Public
    License.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
package net.channel.handler;

import client.MapleCharacter;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import client.MapleClient;
import client.MaplePet;
import client.MapleRing;
import java.sql.Connection;
import tools.DatabaseConnection;
import net.AbstractMaplePacketHandler;
import server.CashItemFactory;
import server.CashItemInfo;
import server.MapleInventoryManipulator;
import tools.MaplePacketCreator;
import tools.data.input.SeekableLittleEndianAccessor;

public final class BuyCSItemHandler extends AbstractMaplePacketHandler {
    public final void handlePacket(SeekableLittleEndianAccessor slea, MapleClient c) {
        if (!c.getPlayer().inCS()) {
            c.getSession().write(MaplePacketCreator.enableActions());
            return;
        }
        final int action = slea.readByte();
        if (action == 3) {
            slea.readByte();
            final int useNX = slea.readInt();
            final int snCS = slea.readInt();
            final CashItemInfo item = CashItemFactory.getInstance().getItem(snCS);
            if (c.getPlayer().getCSPoints(useNX) >= item.getPrice()) {
                c.getPlayer().modifyCSPoints(useNX, -item.getPrice());
            } else {
                c.getSession().write(MaplePacketCreator.enableActions());
                return;
            }
            if (item.getId() >= 5000000 && item.getId() <= 5000100) {
                final int petId = MaplePet.createPet(item.getId());
                if (petId == -1) {
                    c.getSession().write(MaplePacketCreator.enableActions());
                    return;
                }
                MapleInventoryManipulator.addById(c, item.getId(), (short) 1, null, petId);
            } else {
                MapleInventoryManipulator.addById(c, item.getId(), (short) item.getCount(), null);
            }
            c.getSession().write(MaplePacketCreator.showBoughtCSItem(c, item));
            showCS(c);
        } else if (action == 5) {
            try {
                Connection con = DatabaseConnection.getConnection();
                PreparedStatement ps = con.prepareStatement("DELETE FROM wishlist WHERE charid = ?");
                ps.setInt(1, c.getPlayer().getId());
                ps.executeUpdate();
                ps.close();
                int i = 10;
                while (i > 0) {
                    int sn = slea.readInt();
                    if (sn != 0) {
                        ps = con.prepareStatement("INSERT INTO wishlist(charid, sn) VALUES(?, ?) ");
                        ps.setInt(1, c.getPlayer().getId());
                        ps.setInt(2, sn);
                        ps.executeUpdate();
                        ps.close();
                    }
                    i--;
                }
            } catch (SQLException se) {
                se.printStackTrace();
            }
            c.getSession().write(MaplePacketCreator.sendWishList(c.getPlayer().getId()));
            showCS(c);
        } else if (action == 7) {
            slea.readByte();
            byte toCharge = slea.readByte();
            int toIncrease = slea.readInt();
            if (c.getPlayer().getCSPoints(toCharge) >= 4000 && c.getPlayer().getStorage().getSlots() < 48) { // 48 is max.
                c.getPlayer().modifyCSPoints(toCharge, -4000);
                if (toIncrease == 0) {
                    c.getPlayer().getStorage().gainSlots((byte) 4);
                }
                showCS(c);
            }
        } else if (action == 0x1C) { //crush ring (action 28)
            slea.skip(4);
            int toCharge = slea.readInt();
            int SN = slea.readInt();
            String recipient = slea.readMapleAsciiString();
            String text = slea.readMapleAsciiString();
            CashItemInfo ring = CashItemFactory.getInstance().getItem(SN);
            MapleCharacter partner = c.getChannelServer().getPlayerStorage().getCharacterByName(recipient);
            if (partner == null) {
                c.getPlayer().getClient().getSession().write(MaplePacketCreator.serverNotice(1, "The partner you specified cannot be found.\r\nPlease make sure your partner is online and in the same channel."));
            } else {
                if (partner.getGender() == c.getPlayer().getGender()) {
                    c.getPlayer().dropMessage("You and your partner are the same gender, please buy a friendship ring.");
                    return;
                }
                c.getSession().write(MaplePacketCreator.showBoughtCSItem(c, ring));
                c.getPlayer().modifyCSPoints(toCharge, -ring.getPrice());
                MapleRing.createRing(c, ring.getId(), c.getPlayer().getId(), c.getPlayer().getName(), partner.getId(), partner.getName(), text);
                c.getPlayer().getClient().getSession().write(MaplePacketCreator.serverNotice(1, "Successfully created a ring for both you and your partner!"));
            }
            c.getSession().write(MaplePacketCreator.showNXMapleTokens(c.getPlayer()));
        } else if (action == 31) { // everything is 1 meso...
            int itemId = slea.readInt();
            if (c.getPlayer().getMeso() > 0) {
                if (itemId == 4031180 || itemId == 4031192) {
                    c.getPlayer().gainMeso(-1, false);
                    MapleInventoryManipulator.addById(c, itemId, (short) 1, null);
                    c.getSession().write(MaplePacketCreator.showBoughtCSQuestItem(itemId));
                }
            }
            showCS(c);
        } else if (action == 0x22) {
            slea.skip(5);
            int payment = slea.readByte();
            slea.skip(3);
            int snID = slea.readInt();
            CashItemInfo ring = CashItemFactory.getInstance().getItem(snID);
            String sentTo = slea.readMapleAsciiString();
            int available = slea.readShort() - 1;
            String text = slea.readAsciiString(available);
            slea.readByte();
            MapleCharacter partner = c.getChannelServer().getPlayerStorage().getCharacterByName(sentTo);
            if (partner == null) {
                c.getPlayer().dropMessage("The partner you specified cannot be found.\r\nPlease make sure your partner is online and in the same channel.");
            } else {
                c.getSession().write(MaplePacketCreator.showBoughtCSItem(c, ring));
                c.getPlayer().modifyCSPoints(payment, -ring.getPrice());
                MapleRing.createRing(c, ring.getId(), c.getPlayer().getId(), c.getPlayer().getName(), partner.getId(), partner.getName(), text);
                c.getPlayer().getClient().getSession().write(MaplePacketCreator.serverNotice(1, "Successfully created a ring for both you and your partner!"));
            }
            c.getSession().write(MaplePacketCreator.showNXMapleTokens(c.getPlayer()));
        } else {
            System.out.println(slea.toString());
        }
    }

    private static final void showCS(MapleClient c) {
        c.getSession().write(MaplePacketCreator.showNXMapleTokens(c.getPlayer()));
        c.getSession().write(MaplePacketCreator.enableCSUse0());
        c.getSession().write(MaplePacketCreator.enableCSUse1());
        c.getSession().write(MaplePacketCreator.enableCSUse2());
        c.getSession().write(MaplePacketCreator.enableCSUse3());
        c.getSession().write(MaplePacketCreator.enableActions());
    }
}
